package com.qidian.permission.service.impl;

import com.qidian.permission.entity.User;
import com.qidian.permission.mapper.UserMapper;
import com.qidian.permission.service.UserService;
import com.qidian.permission.util.PagerHelper;
import com.qidian.permission.util.PerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Author 32郗建狄
 * @Company GX631
 * Time 2023/10/18 18:17
 * Description
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public PerResult selectById(Long userId) {
        User user = null;
        if ((user = userMapper.selectById(userId))!=null){
            return PerResult.ok(user);
        }
        return PerResult.empty();
    }

    @Override
    public PerResult addUser(User user) {
        if (user != null && userMapper.selectByUserName(user.getUserName()) != null){
            return PerResult.duplicate("该用户已存在");
        }
        return PerResult.updateIsOk(userMapper.addUser(user));
    }

    @Override
    public PerResult selectByPage(User user, int page, int limit) {
        PagerHelper<User> pager = new PagerHelper<>();
        pager.setCurr(page);    //设置当前页
        pager.setLimit(limit);  //设置查询总页数
        pager.setTotal(userMapper.selectCount(user));   //设置总页数
        pager.setData(userMapper.selectByPage(user,(page - 1) * limit,limit));
        pager.setMaxPageNum((int)(Math.ceil(pager.getTotal() * 1.0 / limit)));
        return PerResult.ok(pager);
    }

    @Override
    public PerResult update(User user) {
        // 校验是否重复
        User userTemp = userMapper.selectByUserName(user.getUserName());
        if(userTemp != null && !userTemp.getUserId().equals(user.getUserId())){
            return PerResult.duplicate("用户名重复");
        }
        return PerResult.updateIsOk(userMapper.update(user));
    }

    @Override
    public PerResult deleteByUserId(Long userId) {
        if (Objects.nonNull(userId)){
            userMapper.deteleByUserId(userId);
                return PerResult.ok();
        }
        return PerResult.empty();
    }

    @Override
    public PerResult deletesByUserId(Long[] userIds) {

            int count = userMapper.deletesByUserId(userIds);
            return PerResult.ok(count+"");


    }
}
